<?



/**! Lo level sql class for PostgreSQL

    Used by soSQL

    This collection of functions (libary) is licensed under GPL2.
    See LICENSE or www.gnu.org for more details.
 */

/** soOpenDbConn($Database, $Options = "")
    Returns true (1) if connection to database was established, or false (0)
    if it failed.

    $Options =  soSet of keys/value pairs:
                  Key         Value
                  database    database name
                  host        host to connect to
                  username    as who to connect
                  password    well, guess
                  port        port to connect through
 */
function soOpenDbConn($Options) {

    $connstr = "";
    /* some keys are called by different name under postgres, so better use them */
    $keys = $Options->getKeys();
    $kcount = count($keys);
    for ($k = 0; $k < $kcount; $k++) {
        switch ($keys[$k]) {
            case "database": $connstr .= "dbname";
                             break;
            case "username": $connstr .= "user";
                             break;
            default:         $connstr .= $keys[$k];
        }; // switch
        $connstr .= "=".$Options->getItem($keys[$k])." ";
    }; // for $k

    $conn = pg_pconnect($connstr);
    if ($conn) {
        /* is this obsolete? ... set datestyle to EUROPEAN for the connection */
#        $result = @pg_exec($conn, "SET DATESTYLE TO 'European'");
    };

    soDebug("soOpenDbConn(pg)->options='".$connstr.
            "' return=$conn", 5);
    return $conn;
}; // soOpenDbConn


/** Closes db connection
 */
function soCloseDbConn($ConnID) {
    @pg_close($ConnID);
}; // soCloseDbConn


/** Executes an sql statement.
 *  >$ConnID int Connection ID opened by soOpenDbConn
 *  >$Clause str SQL statement to execute.
 *  >$ResultSet array/array Used with SELECT clause to return result set. Each
 *      row in the 1st array contains a row and each row all column specified
 *      by the SELECT statement.
 *  >$Limit int Used with SELECT clause to limit the number of rows returned
 *      back.
 *  <:int Returns true(1) on success or false(0) on failure.
 *      !select col1, col2, col3 from tablex would return x number of rows, each
 *      having 3 items.
 */
function soRunSqlClause($ConnID, $Clause, &$ResultSet, $Limit = 0) {
    if ((!$ConnID) || ($Clause == "")) return 0; // <-- EXIT

    $result = @pg_exec($ConnID, $Clause);
    soDebug("sosqlpg run: $Clause => $result", 5);

    if ($result) {
        $ResultSet = array();
        $rowcount = @pg_numrows($result);
        if ($Limit > 0) $rowcount = min($Limit, $rowcount);
        for ($i = 0; $i < $rowcount; $i++) {
            $ResultSet[$i] = @pg_fetch_row($result, $i);
        }; // for ($i...
    }; // $result

    return ($result != 0);
}; // soRunSqlClause


?>
